import Middle from "../Middle";
import Utils from "../Utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PicTagImgSprite extends cc.Sprite {

    @property(cc.String)
    imgUrl: string = '';

    parent: Middle = null;

    view: boolean = false;

    touched = false;

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        if (this.imgUrl.length !== 0) {
            cc.assetManager.loadRemote(this.imgUrl, (err, texture: cc.Texture2D) => {
                if (err) {
                    // console.error(err);
                    return;
                }
                this.spriteFrame = new cc.SpriteFrame(texture);
            });
        }

        Utils.addCusorPointerEvents(this.node);

    }

    update(dt: number) {
        if (this.spriteFrame && !this.view) {
            let texture = this.spriteFrame.getTexture();
            if (texture) {
                // this.node.width = this.parent.imgWidth;
                // 丝滑改变图像尺寸
                this.node.width += (this.parent.imgWidth - this.node.width) * dt * 10;
                this.node.height = this.node.width * texture.height / texture.width;
            }
        }

        if (Math.abs(this.to_szoom - this.szoom) > 1e-1) {
            this.szoom += (this.to_szoom - this.szoom) * dt * 10;
            this.node.scale = 1.1 ** this.szoom;
        }
    }

    start() {
        this.node.on(cc.Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    szoom = 0;
    to_szoom = 0;

    onMouseWheel(e: cc.Event.EventMouse) {
        this.to_szoom = this.to_szoom + e.getScrollY() / 120;
    }

    onTouchStart(e: cc.Event.EventTouch) {
        this.touched = true;
    }

    onTouchMove(e: cc.Event.EventTouch) {

    }

    onTouchCancel(e: cc.Event.EventTouch) {
        this.touched = false;
    }

    onTouchEnd(e: cc.Event.EventTouch) {
        this.touched = false;

        if (e.getDelta().len() < 0.1) {
            this.view = !this.view;
            if (this.view) {
                let texture = this.spriteFrame.getTexture();
                let width = this.parent.node.width;
                let height = width * texture.height / texture.width;
                cc.log((this.node.width - width));
                cc.tween(this.node)
                    .to(Math.abs(this.node.width - width) / 10000, { width: width, height: height }, { easing: 'smooth' })
                    .start();
            }
        }
    }

}
